<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/8/3
 * Time: 16:39
 */

namespace app\repository\wechat;


class CustomService
{
    private $appid;
    private $appsecret;
    private $access_token;
    public function __construct()
    {
        $value = db('wx_config')->where([ 'key' => 'SHOPWCHAT'])->value('value');
        $value = json_decode($value);
        $this->appid = $value->appid;
        $this->appsecret = $value->appsecret;

        //获取并更新access_token
        $acc = db('wx_config')->where('key','ACCESS')->find();
        if(time() - $acc['create_time'] <= 7100){
            $this->access_token = $acc['value'];
        }else{
            $this->access();
        }
    }

    /**
     * 添加客服
     * @return bool
     */
    public function addCust($name){
        $data = [
            'kf_account'=>$name.'@JinJieRongHeDL',
            'nickname'=>'客服-1',
            'password'=>'123456'
        ];
        $res = httpRequest("https://api.weixin.qq.com/customservice/kfaccount/add?access_token=".$this->access_token,"POST",$data);
        $res = json_decode($res,true);

        if($res['errmsg'] && $res['errmsg'] == 'ok')
            return true;
        return false;
    }

    /**
     * 发送客服消息
     * @param array $data
     * @return bool
     */
    public function sendText($openid,$content){
        $data = [
            'touser'=>$openid,
            'msgtype'=>'text',
            'text'=>[
                'content'=>$content
            ]
        ];
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $res = httpRequest("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token,"POST",$data);
        $res = json_decode($res,true);
        if($res['errmsg'] && $res['errmsg'] == 'ok')
            return true;
        return false;
    }



    /**
     * 获取access_token
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function access(){
        $t = httpRequest('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appsecret,'GET');
        $t = json_decode($t);
        $this->access_token = $t->access_token;
        return db('wx_config')->where('key','ACCESS')->update(['create_time'=>time(),'value'=>$t->access_token]);
    }
}